package com.closer.service.biz.chatHistory.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.closer.service.biz.app.service.AppService;
import com.closer.service.biz.chatHistory.dto.ChatHistoryQueryRequest;
import com.closer.service.biz.chatHistory.enums.ChatHistoryMessageTypeEnum;
import com.closer.service.biz.chatHistory.validator.HistoryValidator;
import com.closer.service.biz.user.dto.vo.LoginUserVO;
import com.closer.service.support.constant.UserConstant;
import com.closer.service.support.exception.ErrorCode;
import com.closer.service.support.exception.ThrowUtils;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.closer.service.biz.chatHistory.entity.ChatHistory;
import com.closer.service.repository.ChatHistoryMapper;
import com.closer.service.biz.chatHistory.service.ChatHistoryService;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 对话历史 服务层实现。
 *
 * @author closer
 */
@Service
@Slf4j
public class ChatHistoryServiceImpl extends ServiceImpl<ChatHistoryMapper, ChatHistory>  implements ChatHistoryService{

    private final HistoryValidator validator;

    private final AppService appService;

    public ChatHistoryServiceImpl(HistoryValidator validator,@Lazy AppService appService) {
        this.validator = validator;
        this.appService = appService;
    }

    @Override
    public boolean addChatMessage(Long appId, String message, String messageType, Long userId){
        validator.addValidate(appId,message,messageType,userId);
        //验证消息类型是否有效
        var messageTypeEnum = ChatHistoryMessageTypeEnum.getEnumByValue(messageType);
        ThrowUtils.throwIf(messageTypeEnum==null, ErrorCode.PARAMS_ERROR,"消息类型错误");
        var chatHistory = ChatHistory.builder()
                .appId(appId)
                .message(message)
                .messageType(messageType)
                .userId(userId)
                .build();
        return this.save(chatHistory);
    }

    @Override
    public boolean deleteByAppId(Long appId){
        ThrowUtils.throwIf(appId==null || appId<=0, ErrorCode.PARAMS_ERROR,"应用 ID 不能为空");
        var queryWrapper = QueryWrapper.create()
                .eq("appId", appId);
        return this.remove(queryWrapper);
    }

    @Override
    public QueryWrapper getQueryWrapper(ChatHistoryQueryRequest params) {
        var queryWrapper = QueryWrapper.create();
        if(Objects.isNull( params)){
            return queryWrapper;
        }
        var lastCreateTime = params.getLastCreateTime();
        var sortField = params.getSortField();
        var sortOrder = params.getSortOrder();
        queryWrapper.eq("id", params.getId())
                .like("message", params.getMessage())
                .eq("messageType", params.getMessageType())
                .eq("appId", params.getAppId())
                .eq("userId", params.getUserId());
        //游标查询逻辑 - 只使用createTime作为游标
        if(Objects.nonNull(lastCreateTime)){
            queryWrapper.lt("createTime", lastCreateTime);
        }
        if(StrUtil.isNotBlank(sortField)){
            queryWrapper.orderBy(sortField, "ascend".equals(sortOrder));
        } else {
            //默认按创建时间降序排序
            queryWrapper.orderBy("createTime", false);
        }
        return queryWrapper;
    }

    @Override
    public Page<ChatHistory> listAppChatHistoryByPage(Long appId, int pageSize, LocalDateTime lastCreateTime, LoginUserVO loginUser){
        validator.pageValidator(appId,pageSize,loginUser);
        var app = appService.getById(appId);
        ThrowUtils.throwIf(app==null, ErrorCode.NOT_FOUND_ERROR,"应用不存在");
        var isAdmin = UserConstant.ADMIN_ROLE.equals(loginUser.getUserRole());
        var isCreator = app.getUserId().equals(loginUser.getId());
        ThrowUtils.throwIf(!isAdmin && !isCreator, ErrorCode.NO_AUTH_ERROR,"无访问权限");
        //构建查询条件
        var queryRequest = new ChatHistoryQueryRequest();
        queryRequest.setAppId(appId);
        queryRequest.setLastCreateTime(lastCreateTime);
        var queryWrapper = this.getQueryWrapper(queryRequest);
        //分页查询
        return this.page(Page.of(1, pageSize), queryWrapper);
    }

    @Override
    public int loadChatHistoryToMemory(Long appId, MessageWindowChatMemory chatMemory, int maxCount){
        try{
            //构造查询条件，起始点为1而不是0，用于排除最新的用户消息
            var queryWrapper = QueryWrapper.create()
                    .eq(ChatHistory::getAppId,appId)
                    .orderBy(ChatHistory::getCreateTime, false)
                    .limit(1,maxCount);
            var historyList = this.list(queryWrapper);
            if(CollUtil.isEmpty(historyList)){
                return 0;
            }
            //反转列表，确保按时间正序（老的在前，新的在后）
            historyList = historyList.reversed();
            //按时间顺序添加到记忆中
            var loadedCount = 0;
            //先清理历史缓存，防止重复加载
            chatMemory.clear();
            for(var history : historyList){
                if(ChatHistoryMessageTypeEnum.USER.getValue().equals(history.getMessageType())){
                    chatMemory.add(UserMessage.from(history.getMessage()));
                }else if (ChatHistoryMessageTypeEnum.AI.getValue().equals(history.getMessageType())){
                    chatMemory.add(UserMessage.from(history.getMessage()));
                    loadedCount++;
                }
            }
            log.info("成功为appId：{} 加载了 {} 条历史对话",appId,loadedCount);
            return loadedCount;
        }catch (Exception e){
            log.error("加载历史对话失败: {}", e.getMessage());
            return 0;
        }
    }


}
